"""
Author        yongfa
Date          2022-07-14 13:43:24
LastEditTime  2023-07-26 15:42:05
LastEditors   yongfa
Description   功能描述
"""
from flask import current_app
from app.extensions.services import BaseService
from app.extensions.utils.validator import validate_columns
from app.extensions.exception import Failed, Success
from .models import Menu, Apis
from app.modules.v1.dict_data.models import Dict


class RoleService(BaseService):

    def update(self, id):
        api_ids = self.args.get('api_ids', [])
        menu_ids = self.args.get('menu_ids', [])
        dict_ids = self.args.get('dict_ids', [])
        user_ids = self.args.get('user_ids', [])
        data = validate_columns(self.model, self.args)
        item = self.model.get_or_404(id=id)

        if item.is_super_admin:
            raise Failed(message='超级管理员不允许修改')

        if api_ids is not None:
            api_list = Apis.query.filter(Apis.id.in_(api_ids)).all()
            item.apis = api_list
            item.reload_casbin_role()

        if menu_ids is not None:
            menu_list = Menu.query.filter(Menu.id.in_(menu_ids)).all()

            item.menus = menu_list

        if dict_ids is not None:
            dict_list = Dict.query.filter(Dict.id.in_(menu_ids)).all()
            item.dicts = dict_list

        if user_ids is not None:
            from app.modules.v1.user.models import User
            user_list = User.query.filter(User.id.in_(user_ids)).all()
            item.users_list = user_list
        item.update(**data)

        # 修改权限就是全部重置
        # item.reload_casbin_role()

        # 重新加载casbin的策略 #TODO 多进程的导致加载不完整
        # casbin_enforcer.load_policy()
        return Success()

    def delete(self, id):
        """硬删除"""
        conditions = {'id': id}
        if self.conditions:
            conditions.update(self.conditions)
        item = self.model.get_or_404(**conditions)
        if item.is_super_admin:
            raise Failed(message='超级管理员不允许删除')
        if self.model.get(parent_id=item.id):
            return Failed(message='请求先删除子节点')

        if item.users_list:
            return Failed(message='有用户正在使用该角色')
        item.hard_delete()
        return Success()

    def get_all_query(self):
        queryset = super().get_all_query()
        queryset = queryset.filter_by(is_super_admin=False)
        return queryset

    def reload_policy(self):
        """重新加载casbin的策略"""
        # Role.init_data()
        items = self.model.query.all()
        for item in items:
            item.reload_casbin_role()
        return Success()

    def copy(self):
        origin_role_id = self.args.get('origin_role_id')
        origin_role = self.model.get_or_404(id=origin_role_id)
        data = validate_columns(self.model, self.args)
        item = self.model(**data)
        item.apis = origin_role.apis
        item.menus = origin_role.menus
        item.save()
        return Success()


class ApiService(BaseService):
    pass


class MenuService(BaseService):
    pass


def routes_list_data():

    url_map = current_app.url_map
    route_set = []

    for url in url_map.iter_rules():
        data = {}
        data['endpoint'] = url.endpoint
        data['methods'] = list(url.methods)
        data['path'] = url.rule
        route_set.append(data)
    return Success(route_set)
